package game.view;

import game.Board;
import game.Game;
import game.UpdateType;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import javax.swing.*;

import tree.Tree;

/**
 * Numbers panel
 * @author Natchanon Hongladaromp
 *
 */
public class NumbersUI extends JPanel implements Observer
{
	private List<JButton> numbers;
	private Game game;
	private Board board;
	
	/**
	 * Construct for this panel.
	 * @param game game
	 * @param board board
	 */
	public NumbersUI(Game game, Board board)
	{
		this.game = game;
		this.board = board;
		numbers = new ArrayList<JButton>();
		
		initComponents();
	}

	/**
	 * Initial components.
	 */
	private void initComponents()
	{
		this.setLayout(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();
		
		for(int i=0 ; i<4; i++)
		{
			JButton b = new JButton();
			numbers.add(b);
			b.addActionListener(new NumberListener(board, i));
			c.fill = GridBagConstraints.HORIZONTAL;
			c.insets = new Insets(10,5,10,5);
			c.ipadx = 30;
			c.ipady = 20;
			c.gridx = i;
			c.gridy = 0;
			add(b,c);
		}
		
		setSize(new Dimension(120, 20));
	}

	@Override
	public void update(Observable o, Object arg)
	{
		if(arg == UpdateType.UPDATE_NUMBER)
		{
			List<Tree> tree = game.getTree();
			for(int i=0 ; i<4; i++)
			{
				JButton b = numbers.get(i);;
				if(i<tree.size())
				{
					b = numbers.get(i);
					b.setText(String.format("%.0f",tree.get(i).value()));
					for(ActionListener a:b.getActionListeners())
					{
						b.removeActionListener(a);
					}
					b.addActionListener(new NumberListener(board, i));
					b.setEnabled(true);
				}
				else
				{
					b.setText(" ");
					b.setEnabled(false);
				}
			}
		}
	}
}
